from django.shortcuts import render

# Create your views here.

from django_redis import get_redis_connection
from rest_framework.response import Response

from rest_framework.viewsets import ModelViewSet

from apps.spit.models import Spit
from apps.spit.serializer import SpitSerializer


class SpitView(ModelViewSet):
    queryset = Spit.objects.all()
    serializer_class = SpitSerializer

    # 因为可以匿名发表吐槽，因此禁用drf 帮我们做的认证
    def perform_authentication(self, request):
        pass

    # def retrieve(self, request, *args, **kwargs):
    #     spit = self.get_object()
    #     spit.visits += 1
    #     spit.save()
    #     try:
    #         user = self.request.user
    #     except Exception:
    #         user = None
    #     if user is not None and user.is_authenticated:
    #         redis_conn = get_redis_connection('spit')
    #         flag_collect = redis_conn.hget('spit_collect_%s' % user.id, str(id))
    #         flag_thumbup = redis_conn.hget("spit_thumbup_%s" % user.id, str(id))
    #         if flag_collect:
    #             spit.collected = True
    #
    #         if flag_thumbup:
    #             spit.hasthumbup = True
    #
    #
    #     ser = self.get_serializer(instance=spit)
    #     return Response(ser.data)

    # # 获取所有一级吐槽 spit/
    # def list(self, request, *args, **kwargs):
    #     spitList = self.get_queryset().filter(parent=None).order_by("-publishtime")
    #     retSpitList = []
    #     try:
    #         user = self.request.user
    #     except Exception:
    #         user = None
    #
    #     if user is not None and user.is_authenticated:
    #         redis_conn = get_redis_connection('spit')
    #         for spit in spitList:
    #             flag_collect = redis_conn.hget("spit_collect_%s" % user.id,str(spit.id))
    #             flag_thumbup = redis_conn.hget("spit_thumbup_%s"% user.id,str(spit.id))
    #             if flag_collect:
    #                 spit.collected = True
    #             if flag_thumbup:
    #                 spit.hasthumbup = True
    #
    #             retSpitList.append(spit)
    #         else:
    #             retSpitList = spitList
    #         ser = self.get_serializer(instance=retSpitList,many=True)
    #         return Response(ser.data)
